﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;

namespace qiniu_class.Storage
{
    public class ZipEx
    {
        private  FileStream zipToOpen;
        private ZipArchive archive;
        public  void InitZip(string destinationZipFilePath)
        {
             zipToOpen = new FileStream(destinationZipFilePath, FileMode.OpenOrCreate);
             archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update);
        }
        public void AppendZipFile(string staticFile)
        {
            FileStream fileStream = File.Open(staticFile, FileMode.Open);
            AppendZipFile(fileStream, staticFile);
        }
        public  void AppendZipFile(Stream fileStream, string staticFile)
        {
            
            ZipArchiveEntry readmeEntry = archive.CreateEntry(getFileName(staticFile));
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            
                using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
                {
                    writer.Write(buffer);
                    writer.Flush();
                }
            fileStream.Close();
            
        }
        string getFileName(string fullPath)
        {
            string[] splitPath = fullPath.Split('\\');
            return splitPath[splitPath.Length - 1];
        }
        public  void OutPut()
        {
            if (archive!=null)
            {
                archive.Dispose();
                archive = null;
            }
            if (zipToOpen != null)
            {
                zipToOpen.Close();
                zipToOpen.Dispose();
                zipToOpen = null;
            }
        }

        public static void UnZip(string zipfilePath)
        {
            //FileStream zip = new FileStream(zipfilePath, FileMode.Open);
            ZipArchive archive = ZipFile.OpenRead(zipfilePath);
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                Console.WriteLine(entry.FullName);
                if (entry.FullName.EndsWith("\\")) continue;
                entry.Open();
            }
        }

    }
}